import Food from "./Food";
import ScorePanel from "./ScorePanel";
import Snake from "./Snake";

class GameControler{
    food:Food;
    scorePanle:ScorePanel;
    snack:Snake;
    direction = '';
    isLive=true;

    constructor() {
        this.food = new Food();
        this.scorePanle = new ScorePanel();
        this.snack = new Snake();


        this.init();

    }

    init(){
        document.addEventListener('keydown',this.keyDownHandler.bind(this));
        this.run();
    }

    keyDownHandler(event:KeyboardEvent){
        // console.log(enent.key);
        this.direction = event.key;

    }
    run(){
        let x = this.snack.X;
        let y = this.snack.Y;
        switch (this.direction){
            case 'ArrowUp' || 'Up':
                y -= 10;
                break;
            case 'ArrowDown' || 'Down':
                y  += 10;
                break;
            case 'ArrowLeft' || 'Left':
                x -= 10;
                break;
            case 'ArrowRight' || 'Right':
                x += 10;
                break;

        }
        try{
            this.snack.X = x;
            this.snack.Y = y;
            this.eatCheck(x,y);
        }catch (e) {
            alert('游戏结束' + (e as Error).message);
            this.isLive = false;
        }

        this.isLive && setTimeout(this.run.bind(this),300 - (this.scorePanle.level - 1) * 30);
    }

    eatCheck(x:number,y:number){
        if(x === this.food.X && y === this.food.Y){
            this.food.change();
            this.snack.addBody();
            this.scorePanle.addScore();
        }
    }


}


export default GameControler;